<template>
  <div class="login">
    <canvas ref="loginCanvas" class="cavs"></canvas>

    <div class="loginmain">
      <div class="login-title">
        <span>{{pageTitle}}</span>
      </div>

      <el-tooltip v-if="false" class="item" effect="dark" content="切换登录方式" placement="left">
        <el-button @click="dingdingLogin" class="dingdingbtn">
          <el-image
            style="width: 68px; height: 68px"
            :src="hideDing ? require('@/assets/images/inputLogin.png') : require('@/assets/images/qrcode.png')"
            fit="cover"
          ></el-image>
        </el-button>
      </el-tooltip>

      <div class="login-con" v-if="hideDing">
        <div id="login_container"></div>
      </div>
      <form class="login-con" v-else onsubmit="return false">
        <div class="login-user">
          <div class="icon">
            <img src="@/assets/login/cd-icon-username.png" alt />
          </div>
          <input
            type="text"
            v-model="loginInfo.phone"
            name="phone"
            :placeholder="loginInfo.loginType == 1 ? '请输入用户名' : '请输入手机号'"
            autocomplete="off"
            value
          />
        </div>
        <!-- <div class="login-pwd" v-if="loginInfo.loginType == 1"> -->
        <div class="login-pwd" v-if="true">
          <div class="icon">
            <img src="@/assets/login/cd-icon-password.png" alt />
          </div>
          <input
            type="password"
            v-model="loginInfo.password"
            name="pwd"
            placeholder="输入密码"
            autocomplete="off"
            value
          />
        </div>
        <!-- <div class="login-pwd" v-if="loginInfo.loginType == 2"> -->
        <div class="login-pwd" v-if="false">
          <div class="icon">
            <img src="@/assets/login/message.png" alt />
          </div>
          <input
          class="msgInput"
            type="password"
            v-model="loginInfo.code"
            name="pwd"
            placeholder="输入短信验证码"
            autocomplete="off"
            value
          />
          <el-button class="sendBtn" :disabled="disabledSendBtn" type="primary" native-type="submit" @click="sendMsg">{{
            disabledSendBtn ? this.timerCount+'秒后重新发送' : '发送验证码'
            }}</el-button>
        </div>
        <div class="switchInfo" v-if="false">
          <span @click="loginMethod"> {{ loginInfo.loginType == 1 ? '短信验证码登录' : '用户名密码登录' }}
          </span>
          
        </div>
        <div class="login-yan" v-if="false">
          <div class="icon">
            <img src="@/assets/login/yan.png" alt />
          </div>
          <input type="text" name="pwd" placeholder="验证码" autocomplete="off" value />
        </div>
        <div class="login-btn">
          <el-button type="primary" native-type="submit" @click="login" :disabled="disableLoginBtn">登录</el-button>
        </div>
      </form>
    </div>
  </div>
</template>
<script>
import axios from "axios";
import { setRoleRoute } from "@/router/routerConfig";
import {isValidPhoneNumber} from "@/utils/validate";
import { sendMsg} from "@/api/login";
export default {
  //import引入的组件需要注入到对象中才能使用
  components: {},
  data() {
    //这里存放数据
    return {
      pageTitle:process.env.VUE_APP_TITLE,
      loginInfo: {
        // username: "admin",
        // password: "zh321196",
        phone: "",
        password: "",
        code:"",
        loginType:1,//1:密码登录 2:短信登录
      },
      timerCount:60,
      timer:null,
      hideDing: true, //钉钉二维码容器

      disableLoginBtn:false,
      disabledSendBtn:false,
    };
  },
  //监听属性 类似于data概念
  computed: {},
  //监控data中的数据变化
  watch: {},
  //生命周期 - 创建完成（可以访问当前this实例）
  created() {},
  //生命周期 - 挂载完成（可以访问DOM元素）
  mounted() { 
    // login({
    //     level:2,
    //     phone:18790857236,
    //     password:'zh123456'
    // });
    // console.log("this.$store", this.$store, this.$store.state);
    // getShipperAuth();
    // this.login();
    this.setCanvas();
    this.dingdingLogin();
  },
  //方法集合
  methods: {
    async login() {
      if(this.loginInfo.loginType == 1){
        //账号密码登录
        if (!this.loginInfo.phone) {
          this.$message.error("请输入用户名");
          return;
        }
        if (!this.loginInfo.password) {
          this.$message.error("请输入密码");
          return;
        }
      }else{
        //短信验证码登录
        if (!this.loginInfo.phone) {
          this.$message.error("请输入手机号");
          return;
        }
        if (!this.loginInfo.code) {
          this.$message.error("请输入短信验证码");
          return;
        }
      }
      let result = await this.$store.dispatch("user/Login", this.loginInfo);
        if (result.code == 200) {
          this.$message.success("登录成功");
          // setRoleRoute();
          this.$router.push("/index");

          await this.$store.dispatch("user/GetOfficesList");
        }else if(result.code == 306){
          // debugger;
          //登录超过5次 禁用登录按钮
          this.disableLoginBtn = true;
        }

    },
    async sendMsg(){
      if(this.disabledSendBtn) return;
      const isPhone = isValidPhoneNumber(this.loginInfo.phone);
      console.log('isPhone',isPhone);
      if(isPhone){
        //发送短信
        let result = await sendMsg({
          phone:this.loginInfo.phone
        });
        if(result.code == 200){
          //发送成功 倒计时开始
          this.setTimer();
        }else{
          this.$message.error(result.msg);
        }
      }else{
        this.$message.error("请输入正确的手机号");
      }
      
    },
    setTimer(){
      this.disabledSendBtn = true;
      this.timer = setInterval(()=>{
        this.timerCount--;
        if(this.timerCount <= 0){
          //倒计时结束
          this.timerCount = 60;
          this.disabledSendBtn = false;
          clearInterval(this.timer);
        }
      },1000)
    },
    loginMethod(){
      if(this.loginInfo.loginType == 1){
        //显示短息验证码登录
        this.loginInfo.loginType = 2
      }else{
        //显示账号密码登录
        this.loginInfo.loginType = 1;
      }
    },
    dingdingLogin() {
      if (this.hideDing) {
        var con = document.querySelector(".login-con");
        var iframe = con.querySelector("iframe");
        if (iframe) {
          iframe.remove();
        }
      }
      this.hideDing = !this.hideDing;
      if (this.hideDing == false) {
        return;
      }

      this.$nextTick(() => {
        /*
         * 解释一下goto参数，参考以下例子：*/
        let origin = location.origin,
          pathname = location.pathname;
        var url = encodeURIComponent(origin + pathname + "#/dingding");
        var goto = encodeURIComponent(
          "https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dinggtinmoi01k3s5yrr&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=" +
            url
        );
        var obj = DDLogin({
          id: "login_container", //这里需要你在自己的页面定义一个HTML标签并设置id，例如<div id="login_container"></div>或<span id="login_container"></span>
          goto, //请参考注释里的方式
          style:
            "border:none;background-color:rgba(255,255,255,0.4);color:#fff;",
          width: "365",
          height: "400"
        });

        var handleMessage = function(event) {
          var origin = event.origin;
          // console.log("origin", event.origin);
          if (origin == "https://login.dingtalk.com") {
            //判断是否来自ddLogin扫码事件。
            var loginTmpCode = event.data;
            //获取到loginTmpCode后就可以在这里构造跳转链接进行跳转了

            // console.log("loginTmpCode", loginTmpCode);
            window.location.href = `https://oapi.dingtalk.com/connect/oauth2/sns_authorize?appid=dinggtinmoi01k3s5yrr&response_type=code&scope=snsapi_login&state=STATE&redirect_uri=${url}&loginTmpCode=${loginTmpCode}`;
          }
        };
        if (typeof window.addEventListener != "undefined") {
          window.addEventListener("message", handleMessage, false);
        } else if (typeof window.attachEvent != "undefined") {
          window.attachEvent("onmessage", handleMessage);
        }
      });
    },
    setCanvas() {
      try {
        if (/Android|webOS|iPhone|iPod|BlackBerry/i.test(navigator.userAgent)) {
        } else {
          var canvas = this.$refs.loginCanvas,
            ctx = canvas.getContext("2d");
          canvas.width = document.body.clientWidth;
          canvas.height = document.body.clientHeight;
          ctx.lineWidth = 0.3;
          ctx.strokeStyle = new Color(150).style;

          var mousePosition = {
            x: (30 * canvas.width) / 100,
            y: (30 * canvas.height) / 100
          };

          var dots = {
            nb: 250,
            distance: 100,
            d_radius: 150,
            array: []
          };

          function colorValue(min) {
            return Math.floor(Math.random() * 255 + min);
          }

          function createColorStyle(r, g, b) {
            return "rgba(" + r + "," + g + "," + b + ", 0.8)";
          }

          function mixComponents(comp1, weight1, comp2, weight2) {
            return (comp1 * weight1 + comp2 * weight2) / (weight1 + weight2);
          }

          function averageColorStyles(dot1, dot2) {
            var color1 = dot1.color,
              color2 = dot2.color;

            var r = mixComponents(color1.r, dot1.radius, color2.r, dot2.radius),
              g = mixComponents(color1.g, dot1.radius, color2.g, dot2.radius),
              b = mixComponents(color1.b, dot1.radius, color2.b, dot2.radius);
            return createColorStyle(
              Math.floor(r),
              Math.floor(g),
              Math.floor(b)
            );
          }

          function Color(min) {
            min = min || 0;
            this.r = colorValue(min);
            this.g = colorValue(min);
            this.b = colorValue(min);
            this.style = createColorStyle(this.r, this.g, this.b);
          }

          function Dot() {
            this.x = Math.random() * canvas.width;
            this.y = Math.random() * canvas.height;

            this.vx = -0.5 + Math.random();
            this.vy = -0.5 + Math.random();

            this.radius = Math.random() * 2;

            this.color = new Color();
          }

          Dot.prototype = {
            draw: function() {
              ctx.beginPath();
              ctx.fillStyle = this.color.style;
              ctx.arc(this.x, this.y, this.radius, 0, Math.PI, false);
              ctx.fill();
            }
          };

          function createDots() {
            for (var i = 0; i < dots.nb; i++) {
              dots.array.push(new Dot());
            }
          }

          function moveDots() {
            for (var i = 0; i < dots.nb; i++) {
              var dot = dots.array[i];

              if (dot.y < 0 || dot.y > canvas.height) {
                dot.vx = dot.vx;
                dot.vy = -dot.vy;
              } else if (dot.x < 0 || dot.x > canvas.width) {
                dot.vx = -dot.vx;
                dot.vy = dot.vy;
              }
              dot.x += dot.vx;
              dot.y += dot.vy;
            }
          }

          function connectDots() {
            for (var i = 0; i < dots.nb; i++) {
              for (var j = 0; j < dots.nb; j++) {
                var i_dot = dots.array[i];
                var j_dot = dots.array[j];

                if (
                  i_dot.x - j_dot.x < dots.distance &&
                  i_dot.y - j_dot.y < dots.distance &&
                  i_dot.x - j_dot.x > -dots.distance &&
                  i_dot.y - j_dot.y > -dots.distance
                ) {
                  if (
                    i_dot.x - mousePosition.x < dots.d_radius &&
                    i_dot.y - mousePosition.y < dots.d_radius &&
                    i_dot.x - mousePosition.x > -dots.d_radius &&
                    i_dot.y - mousePosition.y > -dots.d_radius
                  ) {
                    ctx.beginPath();
                    ctx.strokeStyle = averageColorStyles(i_dot, j_dot);
                    ctx.moveTo(i_dot.x, i_dot.y);
                    ctx.lineTo(j_dot.x, j_dot.y);
                    ctx.stroke();
                    ctx.closePath();
                  }
                }
              }
            }
          }

          function drawDots() {
            for (var i = 0; i < dots.nb; i++) {
              var dot = dots.array[i];
              dot.draw();
            }
          }

          function animateDots() {
            ctx.clearRect(0, 0, canvas.width, canvas.height);
            moveDots();
            connectDots();
            drawDots();

            requestAnimationFrame(animateDots);
          }
          canvas.addEventListener("mousemove", function(e) {
            mousePosition.x = e.pageX;
            mousePosition.y = e.pageY;
          });
          canvas.addEventListener("mouseleave", function(e) {
            mousePosition.x = canvas.width / 2;
            mousePosition.y = canvas.height / 2;
          });

          createDots();
          requestAnimationFrame(animateDots);
        }
      } catch (e) {}
    }
  }
};
</script>
<style lang='scss' scoped>
.login {
  width: 100%;
  height: 100%;
  background: url("@/assets/login/bg1.png") no-repeat;
  background-size: 100% 100%;
}

.loginmain {
  box-sizing: content-box !important;
  background: #7b7b7b26;
  width: 540px;
  height: 300px;
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  margin: auto;
  padding: 100px 40px 40px 40px;
  box-shadow: -15px 15px 15px rgba(6, 17, 47, 0.7);
  z-index: 99999;
  border-radius: 15px;
}
.switchInfo{
  text-align: right;
  font-size: 14px;
  cursor: pointer;
  color: #409EFF;
  font-weight: bold;
}
.login-title {
  color: #000;
  height: 60px;
  font-size: 25px;
  font-weight: bold;
  text-align: center;
  margin-top: -60px;
}

.login-con {
  height: 240px;
  position: absolute;
  left: 0;
  width: 60%;
  margin: 0 20%;
}

.login-user {
  position: relative;
  background: #eceef0;
  height: 53px;
  line-height: 53px;
  margin-bottom: 15px;
  box-sizing: content-box !important;
  border-radius: 4px;
}

.icon {
  position: absolute;
  z-index: 1;
  left: 36px;
  top: 3px;
  opacity: 1;
  color: #000;
}

.icon img {
  width: 18px;
  height: 18px;
}

.login-con input {
  width: calc(100% - 130px);
  margin-top: -2px;
  background: rgba(57, 61, 82, 0);
  left: 0;
  padding: 10px 65px;
  border-top: 2px solid rgba(57, 61, 82, 0);
  border-bottom: 2px solid rgba(57, 61, 82, 0);
  border-right: none;
  border-left: none;
  outline: none;
  font-family: "Gudea", sans-serif;
  box-shadow: none;
  color: #61bfff !important;
}

.login-pwd,
.login-yan {
  position: relative;
  background: #eceef0;
  height: 53px;
  width: 100%;
  line-height: 53px;
  margin-bottom: 15px;
  box-sizing: content-box !important;
}
.login-pwd{
  .msgInput{
    width: 95px;
  }
}
.sendBtn{
  min-width: 140px;
}
/*
  .login-pwd .icon{
      position: absolute;
      z-index: 1;
      left: 36px;
      top: 8px;
      opacity: .5;
  }*/
.login-btn {
  margin: 40px auto;
  position: relative;

  ::v-deep .el-button {
    width: 100%;
    height: 50px;
  }
}

// .login-btn input {
//     border-radius: 3px;
//     background: #3277fcb8;
//     border: 2px solid #4fa1d9;
//     color: white !important;
//     text-transform: uppercase;
//     font-size: 11px;
//     cursor: pointer;
//     position: absolute;
//     top: 30px;
//     left: 0;
//     right: 0;
//     margin: auto;
//     width: 100%;
//     height: 53px;
//     -webkit-transition-duration: 0.2s;
//     transition-duration: 0.2s;
// }

// .login-btn input:hover {
//     color: white !important;
//     background: #4fa1d9;
//     cursor: pointer;
//     -webkit-transition-property: background, color;
//     transition-property: background, color;
//     -webkit-transition-duration: 0.2s;
//     transition-duration: 0.2s;
// }

::v-deep .dingdingbtn {
  position: absolute;
  top: 2px;
  right: 2px;
  padding: 0;
  background-color: unset;
  clip-path: polygon(0 0, 100% 100%, 100% 0);
  border-radius: 10px;

  .el-image {
    width: 68px;
    height: 68px;
  }
}

.el-tooltip__popper {
  background: rgba(123, 123, 123, 0.1490196078) !important;
}

.login_qrcode_text {
  color: #fff !important;
}
</style>